// pages/user/user.js
var appData = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    hasUserInfo: false,
    canIUseGetUserProfile: false, 
    funList: [{
        url: '/images/licai.png',
        text: '钱包',
        to: '/pages/wallet/wallet'
      },
      {
        url: '/images/dingdanjihe.png',
        text: '订单',
        to: '/pages/order/order'
      },
      {
        url: '/images/juanzeng.png',
        text: '待发货',
        to: '/pages/delivery/delivery'
      },
      {
        url: '/images/xinyuandan.png',
        text: '购物车',
        to: '/pages/shoppingCart/shoppingCart'
      }
    ],
    toolList: [
    //   {
    // //     url: '/images/shuji.png',
    // //     text: '已购的书',
    // //     to: '/pages/user/user'
    // //   },

      {
        url: '/images/ziliaoku.png',
        text: '已发布的书',
        to: '/pages/donatedBook/donatedBook'
      },
      {
        url: '/images/shipping-address.png',
        text: '收货地址',
        to: '/pages/address/address'
      },

      {
        url: '/images/pinlun.png',
        text: '已发布的书评',
        to: '/pages/releaseComment/releaseComment'
      },
      {
        url: '/images/kefu.png',
        text: '客服中心',
        to: '/pages/user/user'
      },
      {
        url: '/images/guize.png',
        text: '平台规则',
        to: '/pages/user/user'
      },

    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },
  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
    // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
        appData.globalData.hasLogin = this.data.hasUserInfo 
        appData.globalData.userInfo = this.data.userInfo
        this.interval(this.data.hasUserInfo)
        wx.login({
          success:(res)=> {
            if (res.code) {
              //发起网络请求
              wx.request({
                url: 'http://124.222.95.170:21311/user/login',
                method: 'GET',
                header: {
                  'Cookie': wx.getStorageSync('sessionid')
                },
                data: {
                  code: res.code,
                  nickName: this.data.userInfo.nickName,
                  avatarUrl: this.data.userInfo.avatarUrl
                },
                success: (res) => {
                  console.log('res',res)
                  wx.removeStorageSync('sessionid');
                  wx.setStorageSync("sessionid", res.header["Set-Cookie"]);
                  console.log('yes')
                }
              })
            } else {
              console.log('登录失败！' + res.errMsg)
            }
          }
        })
      }
    })
  },
  interval(hasLogin){
    if(hasLogin){
      var interval = setInterval(() => {
       this.getChatMsg()
      }, 5000);
    }
  },
  getChatMsg(){
    wx.request({
      url: 'http://124.222.95.170:21311/chat/getMessage',
      method:'GET',
      header: {
        'Cookie': wx.getStorageSync('sessionid')
      },
      success:(res)=>{
        let allMsg = res.data.data
        //有新消息，更新列表
        if(allMsg != null ){
          let len = allMsg.length;
          //获取每个发送方的头像和昵称
          (async ()=>{
            for(let i = 0; i < len; i++){
              let id = allMsg[i].senderId
              let msgLen = allMsg[i].messageList.length
              await this.requestMessage(id,msgLen,allMsg,i);
            }
         })()
        }
        //没有新消息，列表不更新
        else{
          // this.setData({
          //   chatWindows:wx.getStorageSync('localMsg')
          // })
          appData.globalData.chatWindows = wx.getStorageSync('localMsg')
          console.log('没有新消息哦')
        }
      }
    })
  },
  requestMessage(id,msglen,allMsg,i){
    return new Promise((resolve,reject)=>{
      wx.request({
        url: `http://124.222.95.170:21311/user/${id}`,
        method:'GET',
        header: {
          'Cookie': wx.getStorageSync('sessionid')
        },
        success:(res)=>{
          
          //新增数据：头像、昵称、最新消息、首条未读时间
          allMsg[i]['senderName'] = res.data.data.nickName
          allMsg[i]['senderPic']= res.data.data.avatarUrl
          allMsg[i]['latestMsg'] = allMsg[i].messageList[msglen - 1].content
          allMsg[i]['finalTime'] = allMsg[i].messageList[msglen - 1].createTime.substring(10)

          //本地有缓存,判断该用户是否存在
          let arr = []
          if(wx.getStorageSync('localMsg').length != 0){
            
             arr = wx.getStorageSync('localMsg')
            let num = allMsg[i].messageList.length
            let index = arr.findIndex((item)=>{
              return item.senderId === allMsg[i].senderId
            })
            //该用户已存在
            if(index != -1){
              let j = 0
              //在本地找到该用户，并更新最新消息数组
              for(; j < num ; j++){
                arr[index].messageList.push(allMsg[i].messageList[j])
              }
            }
            //该用户不存在,在本地新增用户
            else{
              arr.push(allMsg[i])
            }
          }
          // 本地无缓存，新用户对象直接加入缓存
          else{
            if(i == allMsg.length - 1){
               arr = allMsg
            }
            console.log('此时本地缓存为空')
          }
          //循环结束，更新渲染的数组以及本地缓存
        
            // this.setData({
            //   chatWindows:arr
            // })
            appData.globalData.chatWindows = arr
            wx.setStorageSync('localMsg', appData.globalData.chatWindows)
        
          resolve()                   
        }
      })
    })
  },
})